<template>
  <div class="dashboard-container">
    <!-- 系统概览 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="overview-card">
          <div class="overview-content">
            <div class="overview-text">
              <h2>系统运行状态</h2>
              <p>{{ systemStatus }}</p>
            </div>
            <div class="overview-action">
              <el-button type="primary" @click="refreshData">刷新数据</el-button>
              <el-button v-if="hasAlerts" type="danger" @click="handleAlerts">
                <el-icon><AlarmClock /></el-icon>
                查看紧急求救 ({{ alertsCount }})
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">当前活跃订单</div>
              <div class="data-value">{{ statistics.activeOrders }}</div>
              <div class="data-compare">
                较昨日
                <span :class="statistics.ordersCompare >= 0 ? 'up' : 'down'">
                  {{ statistics.ordersCompare >= 0 ? '+' : '' }}{{ statistics.ordersCompare }}%
                </span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#409EFF"><Tickets /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">在线司机</div>
              <div class="data-value">{{ statistics.onlineDrivers }}</div>
              <div class="data-compare">
                空闲 <span class="normal">{{ statistics.freeDrivers }}</span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#67C23A"><User /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">今日订单总数</div>
              <div class="data-value">{{ statistics.todayOrders }}</div>
              <div class="data-compare">
                完成率 <span class="normal">{{ statistics.completionRate }}%</span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#E6A23C"><Document /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card shadow="hover" class="data-card" :body-style="{ padding: '0px' }">
          <div class="data-card-content">
            <div class="data-card-left">
              <div class="data-title">系统用户</div>
              <div class="data-value">{{ statistics.totalUsers }}</div>
              <div class="data-compare">
                新增 <span class="up">+{{ statistics.newUsers }}</span>
              </div>
            </div>
            <div class="data-card-right">
              <el-icon :size="36" color="#F56C6C"><UserFilled /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时行程和求救信息 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 实时行程 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <el-card class="trip-card">
          <template #header>
            <div class="card-header">
              <span>当前进行中的行程</span>
              <el-button type="primary" size="small" @click="goToMonitor">
                查看详细监控
              </el-button>
            </div>
          </template>
          <div class="trip-map" ref="tripMapRef"></div>
          <div class="trip-list">
            <el-table :data="activeTrips" stripe style="width: 100%" height="200">
              <el-table-column prop="id" label="行程ID" width="120" />
              <el-table-column prop="driverName" label="司机" width="100" />
              <el-table-column prop="passengerCount" label="乘客数" width="80" />
              <el-table-column prop="startTime" label="开始时间" width="150" />
              <el-table-column prop="route" label="路线" />
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button size="small" @click="viewTripDetail(scope.row)">详情</el-button>
                  <el-button size="small" type="primary" @click="trackTrip(scope.row)">跟踪</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
      
      <!-- 求救信息 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <el-card class="alert-card">
          <template #header>
            <div class="card-header">
              <span>紧急求救信息</span>
              <el-tag v-if="alerts.length > 0" type="danger">{{ alerts.length }}条未处理</el-tag>
            </div>
          </template>
          <div class="alert-list">
            <div v-if="alerts.length === 0" class="no-data">
              暂无紧急求救信息
            </div>
            <div v-for="alert in alerts" :key="alert.id" class="alert-item">
              <div class="alert-title">
                <el-icon color="#F56C6C"><Warning /></el-icon>
                <span>{{ alert.title }}</span>
              </div>
              <div class="alert-info">
                <div class="alert-user">{{ alert.userName }} ({{ alert.userType }})</div>
                <div class="alert-time">{{ alert.time }}</div>
                <div class="alert-location">位置: {{ alert.location }}</div>
              </div>
              <div class="alert-actions">
                <el-button type="danger" size="small" @click="handleAlert(alert)">立即处理</el-button>
                <el-button size="small" @click="viewAlertDetail(alert)">查看详情</el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单统计和司机分布 -->
    <el-row :gutter="20" class="mt-20">
      <!-- 订单统计 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="order-card">
          <template #header>
            <div class="card-header">
              <span>订单统计</span>
              <el-radio-group v-model="orderChartType" size="small">
                <el-radio-button label="week">周</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="orderChartRef"></div>
        </el-card>
      </el-col>
      
      <!-- 司机分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="driver-card">
          <template #header>
            <div class="card-header">
              <span>司机分布</span>
            </div>
          </template>
          <div class="chart-container" ref="driverChartRef"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 系统状态
const systemStatus = ref('系统运行正常，所有服务组件正常运行')
const hasAlerts = ref(true)
const alertsCount = ref(2)

// 刷新数据
const refreshData = () => {
  // 模拟数据刷新
  ElMessage.success('数据已刷新')
}

// 处理紧急求救
const handleAlerts = () => {
  router.push('/staff/alerts')
}

// 统计数据
const statistics = reactive({
  activeOrders: 24,
  ordersCompare: 8.3,
  onlineDrivers: 18,
  freeDrivers: 5,
  todayOrders: 156,
  completionRate: 92,
  totalUsers: 3862,
  newUsers: 28
})

// 活跃行程数据
const activeTrips = reactive([
  {
    id: 'T20230510001',
    driverName: '张师傅',
    passengerCount: 3,
    startTime: '2023-05-10 08:30',
    route: '校园北门 → 火车站'
  },
  {
    id: 'T20230510002',
    driverName: '李师傅',
    passengerCount: 2,
    startTime: '2023-05-10 09:15',
    route: '学生公寓 → 商业中心'
  },
  {
    id: 'T20230510003',
    driverName: '王师傅',
    passengerCount: 4,
    startTime: '2023-05-10 10:20',
    route: '图书馆 → 科技园'
  }
])

// 查看行程详情
const viewTripDetail = (trip) => {
  ElMessage.info(`查看行程详情: ${trip.id}`)
}

// 跟踪行程
const trackTrip = (trip) => {
  router.push({
    path: '/staff/monitor',
    query: { tripId: trip.id }
  })
}

// 紧急求救信息
const alerts = reactive([
  {
    id: 'A20230510001',
    title: '乘客紧急求救',
    userName: '李同学',
    userType: '乘客',
    time: '10分钟前',
    location: '华联商场附近',
    status: 'pending'
  },
  {
    id: 'A20230510002',
    title: '司机紧急情况',
    userName: '王师傅',
    userType: '司机',
    time: '15分钟前',
    location: '市中心路段',
    status: 'pending'
  }
])

// 处理求救信息
const handleAlert = (alert) => {
  router.push({
    path: '/staff/alerts',
    query: { alertId: alert.id }
  })
}

// 查看求救详情
const viewAlertDetail = (alert) => {
  ElMessage.info(`查看求救详情: ${alert.id}`)
}

// 前往监控页面
const goToMonitor = () => {
  router.push('/staff/monitor')
}

// 订单图表相关
const orderChartRef = ref(null)
let orderChart = null
const orderChartType = ref('week')

// 监听图表类型变化
watch(orderChartType, (newVal) => {
  initOrderChart()
})

// 初始化订单图表
const initOrderChart = () => {
  if (!orderChartRef.value) return
  
  if (orderChart) {
    orderChart.dispose()
  }
  
  orderChart = echarts.init(orderChartRef.value)
  
  let xAxisData = []
  let completedData = []
  let cancelledData = []
  
  if (orderChartType.value === 'week') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    completedData = [120, 132, 101, 134, 90, 230, 210]
    cancelledData = [20, 12, 11, 14, 9, 23, 21]
  } else {
    xAxisData = Array.from({length: 30}, (_, i) => i + 1)
    completedData = [
      120, 132, 101, 134, 90, 230, 210, 120, 132, 101, 
      134, 90, 230, 210, 120, 132, 101, 134, 90, 230, 
      210, 120, 132, 101, 134, 90, 230, 210, 120, 132
    ]
    cancelledData = completedData.map(val => Math.round(val * 0.1))
  }
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['已完成', '已取消']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '已完成',
        type: 'bar',
        stack: 'total',
        data: completedData,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '已取消',
        type: 'bar',
        stack: 'total',
        data: cancelledData,
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
  
  orderChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    orderChart.resize()
  })
}

// 司机分布图表
const driverChartRef = ref(null)
let driverChart = null

const initDriverChart = () => {
  if (!driverChartRef.value) return
  
  if (driverChart) {
    driverChart.dispose()
  }
  
  driverChart = echarts.init(driverChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '司机分布',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 8, name: '校园区域' },
          { value: 5, name: '市中心' },
          { value: 3, name: '火车站' },
          { value: 2, name: '商业区' },
          { value: 2, name: '住宅区' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  driverChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    driverChart.resize()
  })
}

// 行程地图
const tripMapRef = ref(null)
let tripMap = null

const initTripMap = () => {
  if (!tripMapRef.value) return
  
  // 这里应该集成高德地图API
  // 因为需要引入外部API，这里只做占位处理
  tripMapRef.value.innerHTML = `
    <div style="height: 100%; display: flex; justify-content: center; align-items: center; background-color: #f5f7fa; color: #909399;">
      <div>此处将显示实时行程地图（需集成高德地图API）</div>
    </div>
  `
}

// 组件挂载后初始化图表
onMounted(() => {
  initOrderChart()
  initDriverChart()
  initTripMap()
  
  // 从本地存储获取用户信息
  const storedUsername = localStorage.getItem('username')
  if (storedUsername) {
    // username.value = storedUsername  // 这里有错误，username变量未定义
    // 我们不需要在这里设置用户名，因为本组件中没有显示用户名
  }
})
</script>

<style scoped>
.dashboard-container {
  width: 100%;
  max-width: 100%;
  min-height: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20px;
}

.overview-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #67C23A 0%, #409EFF 100%);
  color: white;
  border: none;
}

.overview-content {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.overview-text {
  flex: 1;
  min-width: 250px;
}

.overview-text h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 24px;
  color: white;
}

.overview-text p {
  margin: 0;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
}

.overview-action {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 10px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
  overflow: hidden;
}

.data-card-content {
  display: flex;
  padding: 20px;
  height: 100%;
}

.data-card-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.data-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.data-compare {
  font-size: 13px;
  color: #909399;
}

.data-compare .up {
  color: #67C23A;
}

.data-compare .down {
  color: #F56C6C;
}

.data-compare .normal {
  color: #409EFF;
}

.data-card-right {
  display: flex;
  align-items: center;
  margin-left: 20px;
}

.trip-card, .alert-card {
  margin-bottom: 20px;
  height: 500px;
}

.trip-map {
  height: 220px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.alert-list {
  height: 440px;
  overflow-y: auto;
}

.alert-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 4px;
  background-color: #fef0f0;
  border-left: 3px solid #F56C6C;
}

.alert-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.alert-title .el-icon {
  margin-right: 10px;
  font-size: 20px;
}

.alert-info {
  margin-bottom: 15px;
  font-size: 14px;
  color: #606266;
}

.alert-user, .alert-time, .alert-location {
  margin-bottom: 5px;
}

.alert-actions {
  display: flex;
  gap: 10px;
}

.order-card, .driver-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart-container {
  height: 340px;
  width: 100%;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #909399;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .trip-card, .alert-card, .order-card, .driver-card {
    height: auto;
  }
  
  .trip-map {
    height: 180px;
  }
  
  .alert-list {
    height: auto;
    max-height: 320px;
  }
  
  .chart-container {
    height: 280px;
  }
}

@media (max-width: 768px) {
  .overview-content {
    flex-direction: column;
  }
  
  .overview-action {
    margin-top: 15px;
  }
  
  .data-card {
    height: 100px;
  }
  
  .data-card-content {
    padding: 15px;
  }
  
  .data-value {
    font-size: 20px;
  }
  
  .trip-map {
    height: 150px;
  }
  
  .chart-container {
    height: 220px;
  }
}
</style> 